package com.developer.loginsample.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.developer.loginsample.R;
import com.developer.loginsample.util.Util;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

public class SignupActivity extends Activity {

	private EditText txtUsername;
	private EditText txtPassword;
	private EditText txtRePassword;
	private EditText txtEmail;
	private Button btnSignup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_signup);
		initializeComponents();
		registerListeners();
	}

	private void initializeComponents() {
		txtUsername = (EditText) findViewById(R.id.txt_signup_username);
		txtPassword = (EditText) findViewById(R.id.txt_signup_password);
		txtRePassword = (EditText) findViewById(R.id.txt_signup_repassword);
		txtEmail = (EditText) findViewById(R.id.txt_signup_email);
		btnSignup = (Button) findViewById(R.id.btn_signup);
	}

	private void registerListeners() {
		btnSignup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setProgressBarIndeterminateVisibility(true);
				String username = txtUsername.getText().toString();
				String password = txtPassword.getText().toString();
				String rePassword = txtRePassword.getText().toString();
				String email = txtEmail.getText().toString();
				if (username.isEmpty() || password.isEmpty() || rePassword.isEmpty() || email.isEmpty()) {
					Util.showAlertDialog(SignupActivity.this, "All field must be filled.");
					setProgressBarIndeterminateVisibility(false);
				} else {
					if (password.equals(rePassword)) {
						ParseUser parseUser = new ParseUser();
						parseUser.setUsername(username);
						parseUser.setPassword(password);
						parseUser.setEmail(email);
						parseUser.signUpInBackground(new SignUpCallback() {
							@Override
							public void done(ParseException exception) {
								if (exception == null) {
									Util.showMessage(SignupActivity.this, "Signup successful.");
									Util.redirectActivity(SignupActivity.this, MainActivity.class);
								} else {
									Util.showAlertDialog(SignupActivity.this, exception.getMessage());
								}
								setProgressBarIndeterminateVisibility(false);
							}
						});
					} else {
						Util.showAlertDialog(SignupActivity.this, "Password mismatch!");
						setProgressBarIndeterminateVisibility(false);
					}
				}
			}
		});
	}

}
